<div class="content">
    <div class="form-row row-fluid" id="div_form_bon_livraison">
        {% include "GdsVenteBundle::BonLivraison/form_bon_livraison.html.twig" %}
        </div>
    </div>
    <script type="text/javascript">


        $(document).ready(function() {
            $('#departement').val({{user.departement.id}})
            $('#departement').attr('disabled', true);
            $('#gds_ventebundle_bonlivraisonclienttype_date').datepicker();
            $('#retour2').hide()
            var fullDate = new Date();
            var twoDigitMonth = fullDate.getMonth()
            twoDigitMonth++
            twoDigitMonth += "";
            if (twoDigitMonth.length == 1)
                twoDigitMonth = "0" + twoDigitMonth;
            var twoDigitDate = fullDate.getDate() + "";
            if (twoDigitDate.length == 1)
                twoDigitDate = "0" + twoDigitDate;
            var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
            $("#gds_ventebundle_bonlivraisonclienttype_date").val(currentDate)
            setInterval(time, 1000);
            $('#form_bon_livraison').validate();
            $('#submit_form_bon_livraison').click(function() {
                $('#gds_ventebundle_bonlivraisonclienttype_reference').focus()
                if ($('#form_bon_livraison').valid()) {
                    $.ajax({
                        url: '{{path("gds_bon_commande_client_livrer")}}',
                        type: "POST",
                        datatype: 'json',
                        data: $('#form_bon_livraison').serialize() + '&articles={"articles":' + JSON.stringify(articles) + '}&heure=' + $('#heure').val() + '&facturable=' + $('#facturable').is(':checked') + '&departement=' + $("#departement option:selected").text() + '&id=' +{{id}},
                        success: function(data) {
                            if (data.success) {
                                $.msgBox({
                                    title: "Bon Livraison",
                                    content: "Enregistrement Effectué avec succés",
                                    type: "info",
                                    buttons: [{value: "OK"}],
                                    success: function(result) {
                                        location.reload();
                                    }
                                });
                            } else {
                                $.msgBox({
                                    title: "Bon Livraison",
                                    content: "Erreur D'enregistrement",
                                    type: "error",
                                    buttons: [{value: "OK"}]
                                });
                            }
                        },
                        error: function(e) {
                            $.msgBox({
                                title: "Bon Livraison",
                                content: "Erreur D'enregistrement",
                                type: "error",
                                buttons: [{value: "OK"}],
                                success: function(result) {
                                }
                            });
                        }
                    })
                }
            })

            Array.prototype.remove = function(v) {
                this.splice(this.indexOf(v) == -1 ? this.length : this.indexOf(v), 1);
            }
            index = 0;
            nb_article = 1;
            // var index_array = Array();
            articles = new Array();
            $container = $('#gds_ventebundle_lignebonlivraisonclienttype');
            index = 0;
            nb_article = 1;
            //remplir lignes si bonCommande a un devis
            {% for l,ligne in lignesdevis %}
                alert({{l}}+'devis')
            add_ligne()
            $('#td_reference_' +{{l}}).html('{{ligne.article.reference}}')
            $('#td_designation_' +{{l}}).html('{{ligne.article.designation}}')
            $('#gds_ventebundle_' +{{l}} + '_quantite').val('{{ligne.quantite|number_format(2)}}')
            setQuantite({{l}})
            $('#td_prix_unitaire_ht_' +{{l}}).html('{{ligne.prixUnitaireHt}}')
            if ({{ligne.prixUnitaireHt}} >{{ligne.article.prixVente}}) {
                $('#tr_' +{{l}}).addClass('green');
                $('#td_prix_unitaire_ht_' +{{l}}).dblclick(function() {
                    if ($('#tr_' +{{l}}).hasClass('red') || $('#tr_' +{{l}}).hasClass('green'))
                        changerPrixVente({{l}},{{ligne.article.prixVente}})
                })
            } else if ({{ligne.prixUnitaireHt}} <{{ligne.article.prixVente}}) {
                $('#tr_' +{{l}}).addClass('red');
                $('#td_prix_unitaire_ht_' +{{l}}).dblclick(function() {
                    if ($('#tr_' +{{l}}).hasClass('red') || $('#tr_' +{{l}}).hasClass('green'))
                        changerPrixVente({{l}},{{ligne.article.prixVente}})
                })
            }
            tva_twig = {{ligne.tauxTva}}
            tva_twig = tva_twig.toFixed(2)
            $('#td_tva_' +{{l}}).html(tva_twig + '%')
            $('#gds_ventebundle_' +{{l}} + '_taux_remise').val('{{ligne.tauxRemise}}')
            $('#gds_ventebundle_' +{{l}} + '_article').val('{{ligne.article.id}}')
            var x = new Object();
            x.reference = $('#td_reference_' + {{l}}).html()
            x.designation = $('#td_designation_' + {{l}}).html()
            x.taux_tva = '{{ligne.tauxTva}}'
            x.remise = '{{ligne.tauxRemise}}'
            x.remise_max = '{{ligne.article.remiseMax}}'
            x.prix_vente = '{{ligne.prixUnitaireHt}}'
            x.quantite = '{{ligne.quantite}}'
            x.prix_vente_min_ttc = x.prix_vente * (1 + (x.taux_tva / 100)) * (1 - (x.remise_max / 100))
            x.name = x.reference + ' : ' + x.designation
            x.id = '{{ligne.article.id}}'
            articles[{{l}}] = x
            completerChamp('{{l}}')
            {% endfor %}
            // remplir lignes si commande n'a pas de devis
            {% for l,ligne in lignesbon %}
            alert({{l}}+'non devis')
            add_ligne()
            $('#td_reference_' +{{l}}).html('{{ligne.reference}}')
            $('#td_designation_' +{{l}}).html('{{ligne.designation}}')
            $('#gds_ventebundle_' +{{l}} + '_quantite').val('{{ligne.quantite|number_format(2)}}')
            setQuantite({{l}})
            $('#td_prix_unitaire_ht_' +{{l}}).html('{{ligne.prixVente}}')
            tva_twig = {{ligne.tauxTva}}
            tva_twig = tva_twig.toFixed(2)
            $('#td_tva_' +{{l}}).html(tva_twig + '%')
            $('#gds_ventebundle_' +{{l}} + '_taux_remise').val('{{ligne.tauxRemise}}')
            $('#gds_ventebundle_' +{{l}} + '_article').val('{{ligne.id}}')
            var x = new Object();
            x.reference = $('#td_reference_' + {{l}}).html()
            x.designation = $('#td_designation_' + {{l}}).html()
            x.taux_tva = '{{ligne.tauxTva}}'
            x.remise = '{{ligne.tauxRemise}}'
            x.remise_max = '{{ligne.remiseMax}}'
            x.prix_vente = '{{ligne.prixVente}}'
            x.quantite = '{{ligne.quantite}}'
            x.prix_vente_min_ttc = x.prix_vente * (1 + (x.taux_tva / 100)) * (1 - (x.remise_max / 100))
            x.name = x.reference + ' : ' + x.designation
            x.id = '{{ligne.id}}'
            articles[{{l}}] = x
            completerChamp('{{l}}')
            {% endfor %}
            RefraichirTaxe()
        });
        function completerChamp(i) {
            var article = getArticle($('#gds_ventebundle_' + i + '_article').val())
            quantite = article.quantite;
            prix_vente = article.prix_vente;
            tva = article.taux_tva;
            remise = article.remise;
            puttc = prix_vente
            puttc *= (1 + tva / 100)
            puttc *= (1 - remise / 100)
            $('#td_prix_u_ttc_' + i).html(puttc.toFixed(3));
            total = puttc * quantite
            $('#td_total_' + i).html(total.toFixed(3));
            $('#gds_ventebundle_' + i + '_taux_remise').spinner({
                min: 0,
                max: article.remise_max,
                step: 1,
                places: 2,
                showOn: 'both'
            });
        }
        function changerPrixVente(i, prix_vente) {
            $.msgBox({
                title: "Changement Prix Vente Ht",
                content: "Voulez-vous changer le Prix Vente à :  " + prix_vente.toFixed(3),
                type: "info",
                buttons: [{value: "OUI"}, {value: "NON"}, {value: "ANNULER"}],
                success: function(result) {
                    if (result == "OUI") {
                        $('#tr_' + i).removeClass('red')
                        $('#tr_' + i).removeClass('green')
                        var article = getArticle($('#gds_ventebundle_' + i + '_article').val())
                        $('#td_prix_unitaire_ht_' + i).html(prix_vente.toFixed(3))
                        var old_remise = article.remise
                        var old_prix_vente = article.prix_vente
                        var taux_tva = article.taux_tva
                        var old_ttc = old_prix_vente * (1 + taux_tva / 100) * (1 - old_remise / 100)
                        article.prix_vente = prix_vente
                        changerPrixTtc(i, old_ttc)
                    }
                }
            });
        }
        function changerPrixTtc(i, old_ttc) {
            $.msgBox({
                title: "Changement Prix Vente Ttc",
                content: "Voulez-vous changer Remise sans modifier PUTTC ?",
                type: "confirm",
                buttons: [{value: "OUI"}, {value: "NON"}],
                success: function(result) {
                    if (result == "OUI") {
                        var article = getArticle($('#gds_ventebundle_' + i + '_article').val())
                        var prix_vente = article.prix_vente
                        var taux_tva = article.taux_tva
                        var r = old_ttc / (prix_vente * (1 + taux_tva / 100))
                        var remise = (1 - r) * 100
                        if (remise < 0) {
                            $.msgBox({
                                title: "Remise Inférieur à 0 !!",
                                content: "Remise changé à 0",
                                type: "info",
                                buttons: [{value: "OK"}],
                            });
                            remise = 0
                            article.remise = remise
                        }
                        if (remise > article.remise_max) {
                            $.msgBox({
                                title: "Remise Max Dépassé",
                                content: "Voulez-vous changer le remise max à : " + remise.toFixed(2) + " ?",
                                type: "confirm",
                                buttons: [{value: "OUI"}, {value: "NON"}],
                                success: function(result) {
                                    if (result == "OUI") {
                                        article.remise_max = remise
                                        $('#gds_ventebundle_' + i + '_taux_remise').spinner({
                                            min: 0,
                                            max: article.remise_max,
                                            step: 1,
                                            places: 2,
                                            showOn: 'both'
                                        });
                                        $('#gds_ventebundle_' + i + '_taux_remise').val(remise.toFixed(2))
                                        RefraichirTaxe()
                                    } else {
                                        remise = article.remise_max
                                    }
                                    $('#gds_ventebundle_' + i + '_taux_remise').keyup()
                                }
                            });
                            article.remise = remise
                        }
                        $('#gds_ventebundle_' + i + '_taux_remise').val(remise.toFixed(2))
                    }
                    completerChamp(i)
                    RefraichirTaxe()
                }
            });
        }
        function changeRemiseClient() {
            articles_to_modify = new Array()
            index_modify = new Array()
            $('#gds_ventebundle_lignebonlivraisonclienttype tr').each(function() {
                var ii = $(this).attr('id');
                ii = ii.split('_');
                ii = ii[1]
                articles_to_modify[articles_to_modify.length] = $('#gds_ventebundle_' + ii + '_article').val()
                index_modify[index_modify.length] = ii

            })
            $.ajax({
                url: '{{path("gds_vente_get_remises_client")}}',
                type: "POST",
                data: {'articles': articles_to_modify, 'raison_social': $('#gds_ventebundle_bonlivraisonclienttype_client').val()},
                dataType: 'json',
                success: function(data) {
                    for (i = 0; i < index_modify.length; i++) {
                        if (data[i] != null) {
                            $('#gds_ventebundle_' + index_modify[i] + '_taux_remise').val(data[i])
                            doRemiseChange(index_modify[i])
                        }
                    }
                    RefraichirTaxe()
                }
            })

        }
        $(document).ready(function() {
            $('#show_article').click(function() {
                art = ""
                for (i = 0; i < articles.length; i++)
                    alert(articles[i].id + "   " + articles[i].reference + "  " + articles[i].quantite + "  " + articles[i].remise)
            })
        })

        </script>

        <input type="hidden" id="heure"/>
        <input type="button" value="article" id="show_article">
